package com.tests;

import be.ac.ulg.montefiore.run.jahmm.Hmm;
import com.qp.CMatrixCalculator;
import com.qp.OutputDistributionCalculator;
import com.qp.QPCaller;

/**
 * Created with IntelliJ IDEA.
 * User: bigmar
 * Date: 12/21/14
 * Time: 2:21 PM
 * To change this template use File | Settings | File Templates.
 */
public class ExpectedEtaCalculator
{
    public static double[] calculateExpectedEta(Hmm hmm) throws Exception {
        double [][] aMatrix=extractAMatrix(hmm);
        double[][] kMatrix= OutputDistributionCalculator.calculate(hmm.getOpdf());
        double[][] cMatrix= CMatrixCalculator.calculate(hmm.getPi(), kMatrix);


        double[] stationaryDistributions=hmm.getPi();
        int length=stationaryDistributions.length;
        double[] calculatedEta=new double[length*length];

        for (int k1=0; k1<length; ++k1)
            for (int k2=0; k2<length; ++k2)
                for (int i=0; i<length; ++i)
                    for (int j=0; j<length; ++j)
                        // The a matrix in the article is column stochastic but here we have a row stochastic, for the sake of building the HMM, and its expected input
                        // This is why we use aMatrix[j][i] and not aMatrix[i][j] like in the article
                        calculatedEta[k1*length+k2]+=kMatrix[k2][i]*kMatrix[k1][j]*aMatrix[j][i]*stationaryDistributions[j];

        double[][] newAMatrix= QPCaller.call(cMatrix, hmm.getPi(), calculatedEta);

        for (int i=0; i<length; ++i)
        {
            for (int j=0; j<length; ++j)
                System.out.print(newAMatrix[i][j]+" ");
            System.out.println();
        }
//        System.exit(1);
        return calculatedEta;
    }
    private static double[][] extractAMatrix(Hmm hmm)
    {
        int length=hmm.nbStates();
        double[][] matrix=new double[length][length];
        for (int i=0; i<length; ++i)
            for (int j=0; j<length; ++j)
            {
                matrix[i][j]=hmm.getAij(i, j);
            }

        return matrix;
    }

}
